//
//  UUIntentOrderManager.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 27/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUIntentOrderManager.h"
#import <UUFoundation/DKDataManager.h>
#import <UUFoundation/UUIncrementDataManager.h>
#import "UUIntentOrderUtility.h"
#import "UUIntentOrderCountRequestModel.h"
#import "UUIntentOrderListRequestModel.h"
#import "UUIntentOrderDetailRequestModel.h"
#import "UUIntentOrderActionRequestModel.h"
#import "UUIntentOrderHistoryRequestModel.h"
#import "UUIntentOrderReceiveNotificationRequestModel.h"

@interface UUIntentOrderManager ()

@property (nonatomic, strong) UUIncrementDataManager *historyDataManager;

@end

@implementation UUIntentOrderManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.historyDataManager = [UUIncrementDataManager managerWithConfiguration:
                                   [UUIncrementDataManagerConfiguration configurationWithRequestModelClass:[UUIntentOrderHistoryRequestModel class]
                                                                                                  isTwoWay:YES
                                                                                            storeContainer:[UUIntentOrderUtility userPrivates]]];
    }
    return self;
}

- (void)asyncFetchIntentCountWithCompleteBlock:(void (^)(NSInteger count, NSError *error))completeBlock {
    UUIntentOrderCountRequestModel *requestModel = [UUIntentOrderCountRequestModel new];
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            UUIntentOrderCountResponseModel *intentOrderCountResponseModel = (UUIntentOrderCountResponseModel *)responseModel;
            BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, intentOrderCountResponseModel.count, nil);
        } else {
            BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, 0, error);
        }
    }];
}

- (void)asyncFetchIntentOrdersWithSince:(id)since
                                 length:(int)length
                          completeBlock:(void (^)(NSArray<UUIntentOrderModel *> *orders, id since, NSError *error))completeBlock {
    UUIntentOrderListRequestModel *requestModel = [UUIntentOrderListRequestModel new];
    requestModel.since = since;
    requestModel.perPage = length;
    
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            UUIntentOrderListResponseModel *orderListResponseModel = (UUIntentOrderListResponseModel *)responseModel;
            BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, orderListResponseModel.insert, orderListResponseModel.since, nil);
        } else {
            BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, nil, nil, error);
        }
    }];
}

- (void)asyncFetchIntentOrderDetailWithOrderId:(NSNumber *)orderId
                                 completeBlock:(void (^)(UUIntentOrderDetailModel *orderDetail, NSError *error))completeBlock {
    UUIntentOrderDetailRequestModel *requestModel = [UUIntentOrderDetailRequestModel new];
    requestModel.orderId = orderId;
    
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, (UUIntentOrderDetailModel *)responseModel, error);
    }];
}

- (void)asyncUpdateIntentOrderWithOrderId:(NSNumber *)orderId
                                    price:(NSNumber *)price
                               actionType:(UUIntentOrderActionType)actionType
                            completeBlock:(void (^)(NSError *error))completeBlock {
    UUIntentOrderActionRequestModel *requestModel = [UUIntentOrderActionRequestModel new];
    requestModel.price = price;
    requestModel.intentOrderId = orderId;
    requestModel.actionType = actionType;
    
    WEAK_SELF();
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        if (error == nil) {
            [weakSelf notifyObserversWithSelector:@selector(intentOrderDidUpdate:withActionType:)
                                    withObjectOne:orderId
                                        objectTwo:@(actionType)];;
        }
        
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)asyncUpdateIntentOrderReceiveNotification:(BOOL)isReceive completeBlock:(void (^)(NSError *error))completeBlock {
    UUIntentOrderReceiveNotificationRequestModel *requestModel = [UUIntentOrderReceiveNotificationRequestModel new];
    requestModel.receiveIntentOrder = isReceive;
    
    [[DKDataManager new] requestWithRequestModel:requestModel completedBlock:^(DKResponseModel *responseModel, NSError *error) {
        BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, error);
    }];
}

- (void)asyncFetchIntentOrderHistoryLisWithSince:(id)since
                                          length:(int)length
                                   completeBlock:(void (^)(NSArray<NSNumber *> *orders, id since, NSError *error))completeBlock {
    NSNumber *orderId = since;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSTimeInterval updateTime = [self fetchIntentHistoryOrderWithOrderId:orderId].updateTime;
        NSArray<NSNumber *> *orders = [self fetchIntentHistoryOrderBeforeUpdateTime:updateTime length:length];
        
        if (orders.count == length) {
            BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, orders, orders.lastObject, nil);
            return;
        }
        
        [self.historyDataManager asyncFetchHistoryWithLength:length completeBlock:^(BOOL hadUpdate, NSError *error) {
            if (error == nil) {
                if (hadUpdate) {
                    NSArray<NSNumber *> *orders = [self fetchIntentHistoryOrderBeforeUpdateTime:updateTime length:length];
                    BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, orders, orders.lastObject, nil);
                } else {
                    BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, orders, orders.lastObject, nil);
                }
            } else {
                BLOCK_SAFE_CALLS_In_Main_Queue(completeBlock, orders, orders.lastObject, error);
            }
        }];
    });
}

- (UUIntentOrderHistoryModel *)fetchIntentHistoryOrderWithOrderId:(NSNumber *)orderId {
    return (UUIntentOrderHistoryModel *)[self.historyDataManager fetchModelWithPrimaryKeyValue:orderId];
}

#pragma mark - Private methods

- (NSArray<id> *)fetchIntentHistoryOrderBeforeUpdateTime:(NSTimeInterval)updateTime length:(int)length {
    NSMutableString *where = [NSMutableString new];
    if (updateTime != 0) {
        [where appendFormat:@"updateTime < %f", updateTime];
    }
    
    return [UUIntentOrderHistoryModel searchColumn:@"id"
                                             where:where
                                           orderBy:@"updateTime desc"
                                            offset:0
                                             count:length];
}

@end
